package com.keyancompany.zhongbaopingtai.utils;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.widget.Toast;

import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;


/**
 * Created by Ken on 2015/11/13.
 */
public class FileHelper {

    private static FileHelper mInstance = new FileHelper();

    public static FileHelper getInstance() {
        return mInstance;
    }

    public static boolean isSdCardExist() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public static String createAvatarPath(String userName) {
        String dir = Constants.PICTURE_DIR;
        File destDir = new File(dir);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File file;
        if (userName != null) {
            file = new File(dir, userName + ".png");
        } else {
            file = new File(dir, new DateFormat().format("yyyy_MMdd_hhmmss",
                    Calendar.getInstance(Locale.CHINA)) + ".png");
        }
        return file.getAbsolutePath();
    }

    public static String getUserAvatarPath(String userName) {
        return Constants.PICTURE_DIR + userName + ".png";
    }

    public static File saveAvatarBitmap(Bitmap bitmap) {
        FileOutputStream out = null;
        File file = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) // 判断是否可以对SDcard进行操作
        {      // 获取SDCard指定目录下
            String sdCardDir = Constants.PICTURE_DIR;
            File dirFile = new File(sdCardDir);  //目录转化成文件夹
            if (!dirFile.exists()) {                //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }                            //文件夹有啦，就可以保存图片啦
            file = new File(sdCardDir, System.currentTimeMillis() + ".jpg");// 在SDcard的目录下创建图片文,以当前时间为其命名

            try {
                out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }


    public interface CopyFileCallback {
        public void copyCallback(Uri uri);
    }

    public static String getRealPath(Context context, Uri uri) {

        if ("content".equalsIgnoreCase(uri.getScheme())) {

            String[] projection = {"_data"};

            Cursor cursor = null;
            try {

                cursor = context.getContentResolver().query(uri, projection, null, null, null);

                int column_index = cursor.getColumnIndexOrThrow("_data");

                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }

            } catch (Exception e) {
                return null;
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {

            return uri.getPath();
        }
        return null;
    }


    public static String getMIMEType(String fName) {
        String type = "";
        String end;
        /* 取得扩展名 */
        if (fName.contains(".")) {
            end = fName.substring(fName.lastIndexOf(".") + 1, fName.length())
                    .toLowerCase();
        } else {
            end = fName.toLowerCase();
        }

		/* 依扩展名的类型决定MimeType */
        if (end.equals("html") || end.endsWith("htmlx")) {
            type = "text/html";
        } else if (end.equals("pdf")) {
            type = "application/pdf";//
        } else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio/*";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video/*";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp")) {
            type = "image/*";
        } else if (end.equals("apk")) {
            /* android.permission.INSTALL_PACKAGES */
            type = "application/vnd.android.package-archive";
        } else if (end.equals("pptx") || end.equals("ppt")) {
            type = "application/vnd.ms-powerpoint";
        } else if (end.equals("docx") || end.equals("doc")) {
            type = "application/msword";
        } else if (end.equals("xlsx") || end.equals("xls")) {
            type = "application/vnd.ms-excel";
        } else if (end.equals("txt")) {
            type = "text/plain";
        } else {
            // /*如果无法直接打开，就跳出软件列表给用户选择 */
            type = "*/*";
        }
        return type;
    }

    public static void openFile(Context context, String paveUrl) {
        try {
            String type = getMIMEType(paveUrl);
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // 设置intent的Action属性
            intent.setAction(Intent.ACTION_VIEW);
            // 获取文件file的MIME类型

            // 设置intent的data和Type属性。
            File file = new File(paveUrl);
            intent.setDataAndType(/* uri */Uri.fromFile(file), type);
            // 跳转
            context.startActivity(intent);
            // Intent.createChooser(intent, "请选择对应的软件打开该附件！");

        } catch (ActivityNotFoundException e) {
            // TODO: handle exception
            Toast.makeText(context, "无法打开此文件", Toast.LENGTH_LONG).show();
        }
    }

    public static int getFileIcon(String fName) {
        int type = -1;
        String end;
        /* 取得扩展名 */
        if (fName.contains(".")) {
            end = fName.substring(fName.lastIndexOf(".") + 1, fName.length())
                    .toLowerCase();
        } else {
            end = fName;
        }
        /* 依扩展名的类型决定MimeType */
        if (end.equals("html") || end.endsWith("htmlx")) {
            type = R.mipmap.file_icon_html;
        } else if (end.equals("pdf")) {
            type = R.mipmap.file_icon_pdf;
        } else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = R.mipmap.file_icon_mp3;
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = R.mipmap.file_icon_video;
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp")) {
            type = R.mipmap.file_icon_jpg;
        } else if (end.equals("apk")) {
            /* android.permission.INSTALL_PACKAGES */
            type = R.mipmap.file_icon_apk;
        } else if (end.equals("pptx") || end.equals("ppt")) {
            type = R.mipmap.file_icon_ppt;
        } else if (end.equals("docx") || end.equals("doc")) {
            type = R.mipmap.file_icon_doc;
        } else if (end.equals("xlsx") || end.equals("xls")) {
            type = R.mipmap.file_icon_xls;
        } else if (end.equals("txt")) {
            type = R.mipmap.file_icon_txt;
        } else if (end.equals("zip")) {
            type = R.mipmap.file_icon_zip;
        } else {
            // /*如果无法直接打开，就跳出软件列表给用户选择 */
            type = R.mipmap.file_icon_unknow;
        }
        return type;
    }
}